{% extends "admin/layout.html" %}


{% block title %}编辑门禁设备 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}

{% block content %}
    <div class="container-fluid">
        <!-- 页面标题和操作区域 -->
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 gap-3">
            <div>
                <h1 class="h3 mb-0 text-gray-800 fw-bold">
                    <i class="fas fa-edit me-2 text-primary"></i>编辑门禁设备
                </h1>
                <p class="text-muted mb-0">修改设备配置信息</p>
            </div>
            <div class="d-flex gap-2">
                <button type="submit" form="deviceForm" class="btn btn-success btn-sm">
                    <i class="fas fa-save me-1"></i>更新设备
                </button>
                <a href="{{ url_for('zktime.device_list') }}" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-times me-1"></i>取消
                </a>
            </div>
        </div>

        <!-- 设备信息卡片 -->
        <div class="card shadow-sm border-0">
            <div class="card-header py-2 bg-white d-flex align-items-center">
                <i class="fas fa-info-circle me-2 text-primary"></i>
                <h6 class="m-0 font-weight-bold text-primary mb-0">设备基本信息</h6>
            </div>
            <div class="card-body p-4">
                <form id="deviceForm" method="POST" action="{{ url_for('zktime.device_edit', device_id=device.id) }}">
                    <div class="row g-3">
                        <!-- 设备名称 -->
                        <div class="col-md-6">
                            <label for="name" class="form-label required">
                                <i class="fas fa-tag me-1 text-muted"></i>设备名称
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-server"></i></span>
                                <input type="text" class="form-control" id="name" name="name"
                                       value="{{ device.name }}" required placeholder="例如：主入口门禁">
                            </div>
                            <div class="form-text">为设备指定一个易识别的名称</div>
                        </div>

                        <!-- IP地址 -->
                        <div class="col-md-6">
                            <label for="ip_address" class="form-label required">
                                <i class="fas fa-network-wired me-1 text-muted"></i>IP地址
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-laptop-code"></i></span>
                                <input type="text" class="form-control" id="ip_address" name="ip_address"
                                       value="{{ device.ip_address }}" required placeholder="例如：192.168.1.100">
                            </div>
                            <div class="form-text">设备的IP地址或主机名</div>
                        </div>

                        <!-- 端口 -->
                        <div class="col-md-4">
                            <label for="port" class="form-label">
                                <i class="fas fa-plug me-1 text-muted"></i>端口
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-exchange-alt"></i></span>
                                <input type="number" class="form-control" id="port" name="port"
                                       value="{{ device.port or 4370 }}" min="1" max="65535">
                            </div>
                            <div class="form-text">默认端口：4370</div>
                        </div>

                        <!-- 协议 -->
                        <div class="col-md-4">
                            <label for="protocol" class="form-label">
                                <i class="fas fa-link me-1 text-muted"></i>协议
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-project-diagram"></i></span>
                                <select class="form-select" id="protocol" name="protocol">
                                    <option value="TCP" {% if device.protocol == 'TCP' %}selected{% endif %}>TCP</option>
                                    <option value="UDP" {% if device.protocol == 'UDP' %}selected{% endif %}>UDP</option>
                                </select>
                            </div>
                        </div>

                        <!-- 设备密码 -->
                        <div class="col-md-4">
                            <label for="password" class="form-label">
                                <i class="fas fa-lock me-1 text-muted"></i>设备密码
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-key"></i></span>
                                <input type="password" class="form-control" id="password" name="password"
                                       value="{{ device.password }}" placeholder="输入设备密码">
                            </div>
                            <div class="form-text">设备访问密码（可选）</div>
                        </div>

                        <!-- 设备描述 -->
                        <div class="col-12">
                            <label for="description" class="form-label">
                                <i class="fas fa-align-left me-1 text-muted"></i>设备描述
                            </label>
                            <textarea class="form-control" id="description" name="description"
                                      rows="3" placeholder="设备位置、型号或其他相关信息">{{ device.description }}</textarea>
                        </div>
                    </div>

                    <!-- 设备预览 -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <h6 class="text-primary mb-3">
                                <i class="fas fa-eye me-2"></i>设备信息预览
                            </h6>
                            <div class="card bg-light border">
                                <div class="card-body">
                                    <div class="d-flex flex-wrap gap-3">
                                        <div class="device-preview-item">
                                            <span class="text-muted">名称：</span>
                                            <span id="preview-name">{{ device.name }}</span>
                                        </div>
                                        <div class="device-preview-item">
                                            <span class="text-muted">IP：</span>
                                            <span id="preview-ip">{{ device.ip_address }}</span>
                                        </div>
                                        <div class="device-preview-item">
                                            <span class="text-muted">端口：</span>
                                            <span id="preview-port">{{ device.port or 4370 }}</span>
                                        </div>
                                        <div class="device-preview-item">
                                            <span class="text-muted">协议：</span>
                                            <span id="preview-protocol">{{ device.protocol }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <!-- 操作按钮 -->
            <div class="card-footer bg-white d-flex justify-content-end pt-0">
                <button type="submit" form="deviceForm" class="btn btn-success me-2">
                    <i class="fas fa-save me-1"></i>更新设备
                </button>
                <a href="{{ url_for('zktime.device_list') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-times me-1"></i>取消
                </a>
            </div>
        </div>

        <!-- 设备状态卡片 -->
        <div class="card shadow-sm border-0 mt-4">
            <div class="card-header py-2 bg-white">
                <h6 class="m-0 font-weight-bold text-primary mb-0">
                    <i class="fas fa-wifi me-2 text-info"></i>设备连接状态
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <!-- 设备状态卡片中的连接状态部分 -->
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <!-- 添加 id 用于更新指示灯颜色 -->
                                <div id="statusIndicator" class="status-indicator bg-{{ 'success' if device.status == 1 else 'danger' if device.status == 0 else 'warning' }}"></div>
                            </div>
                            <div>
                                <div class="fw-medium">连接状态</div>
                                <!-- 添加 id 用于更新状态文本 -->
                                <div id="statusText" class="text-{{ 'success' if device.status == 1 else 'danger' if device.status == 0 else 'warning' }} small">
                                    {{ '在线（最后连接时间：' + device.last_heartbeat.strftime('%Y-%m-%d %H:%M:%S') if device.last_heartbeat else '未知' }}
                                    {% if device.status == 0 %}| 离线
                                    {% elif device.status == 1 %}| 在线
                                    {% else %}| 故障
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <div class="status-indicator bg-secondary"></div>
                            </div>
                            <div>
                                <div class="fw-medium">设备信息</div>
                                <div class="text-muted small">
                                    型号：{{ device.model|default('未知') }} |
                                    固件版本：{{ device.firmware|default('未知') }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 测试连接按钮（AJAX实现） -->
                <div class="d-flex justify-content-end mt-4">
                    <button type="button" id="testConnectionBtn" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-sync-alt me-1"></i>测试连接
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 提示消息容器 -->
    <div id="alertContainer" style="position: fixed; top: 20px; right: 20px; z-index: 1050;"></div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 设备信息预览功能
            const nameInput = document.getElementById('name');
            const ipInput = document.getElementById('ip_address');
            const portInput = document.getElementById('port');
            const protocolInput = document.getElementById('protocol');
            const previewName = document.getElementById('preview-name');
            const previewIp = document.getElementById('preview-ip');
            const previewPort = document.getElementById('preview-port');
            const previewProtocol = document.getElementById('preview-protocol');

            if (nameInput && ipInput && portInput && protocolInput &&
                previewName && previewIp && previewPort && previewProtocol) {

                function updatePreview() {
                    previewName.textContent = nameInput.value || '-';
                    previewIp.textContent = ipInput.value || '-';
                    previewPort.textContent = portInput.value || '-';
                    previewProtocol.textContent = protocolInput.value || '-';
                }

                [nameInput, ipInput, portInput, protocolInput].forEach(el => {
                    el.addEventListener('input', updatePreview);
                });

                updatePreview();
            }

// 测试连接功能
            const testConnectionBtn = document.getElementById('testConnectionBtn');
            if (testConnectionBtn) {
                testConnectionBtn.addEventListener('click', function() {
                    console.log('测试连接按钮被点击！');
                    const originalText = testConnectionBtn.innerHTML;
                    const originalIcon = testConnectionBtn.querySelector('i').className;

                    // 显示加载状态
                    testConnectionBtn.disabled = true;
                    testConnectionBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>测试中...';

                    // 发送AJAX请求
                    fetch('{{ url_for("zktime.device_test", device_id=device.id) }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'X-Requested-With': 'Ajax'
                        },
                        body: 'csrf_token={{ csrf_token() }}'
                    })
                        .then(response => response.json())
                        .then(data => {
                            // 显示提示消息
                            showAlert(data.message, data.success ? 'success' : 'danger');

                            // 关键：更新设备状态显示（如果后端返回了最新状态）
                            if (data.success && data.data) {
                                const { status, last_heartbeat } = data.data;

                                // 更新状态指示灯颜色
                                const statusIndicator = document.getElementById('statusIndicator');
                                statusIndicator.className = `status-indicator bg-${
                                    status === 1 ? 'success' :
                                        status === 0 ? 'danger' :
                                            'warning'
                                }`;

                                // 更新状态文本（状态标签 + 最后连接时间）
                                const statusText = document.getElementById('statusText');
                                let statusLabel = '';
                                if (status === 1) {
                                    statusLabel = `在线（最后连接时间：${last_heartbeat || '未知'}）`;
                                } else if (status === 0) {
                                    statusLabel = '离线';
                                } else {
                                    statusLabel = '故障';
                                }
                                statusText.textContent = statusLabel;
                                // 更新文本颜色类（可选，根据需求调整）
                                statusText.className = `text-${
                                    status === 1 ? 'success' :
                                        status === 0 ? 'danger' :
                                            'warning'
                                } small`;
                            }

                            // 恢复按钮状态
                            testConnectionBtn.disabled = false;
                            testConnectionBtn.innerHTML = originalText;
                            testConnectionBtn.querySelector('i').className = originalIcon;
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showAlert('测试连接失败，请检查网络连接', 'danger');
                            testConnectionBtn.disabled = false;
                            testConnectionBtn.innerHTML = originalText;
                            testConnectionBtn.querySelector('i').className = originalIcon;
                        });
                });
            }

            // 显示提示消息的函数
            function showAlert(message, type) {
                const alertContainer = document.getElementById('alertContainer');
                const alertId = 'alert-' + Date.now();

                const alertHtml = `
            <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show" role="alert" style="min-width: 300px;">
                <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;

                alertContainer.insertAdjacentHTML('beforeend', alertHtml);

                // 5秒后自动消失
                setTimeout(() => {
                    const alertElement = document.getElementById(alertId);
                    if (alertElement) {
                        alertElement.remove();
                    }
                }, 5000);
            }


        });
    </script>

    <style>
        /* 保留原有样式 */
        .required:after { content: " *"; color: #dc3545; }
        .form-label { font-weight: 500; margin-bottom: 0.3rem; }
        .input-group-text { min-width: 40px; justify-content: center; }
        .form-text { font-size: 0.85rem; color: #6c757d; }
        .device-preview-item {
            background: #e9ecef; padding: 0.5rem 1rem; border-radius: 0.25rem; font-size: 0.9rem;
        }
        .status-indicator {
            width: 24px; height: 24px; border-radius: 50%;
        }
        .card-footer { border-top: 1px solid rgba(0,0,0,.05); }
        .table th { font-weight: 600; vertical-align: middle; background-color: #f8f9fa; }

        /* 新增样式 */
        #testConnectionBtn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        #testConnectionBtn {
            position: relative;
            z-index: 1000; /* 确保按钮在最上层 */
        }
    </style>
{% endblock %}
